from typing import Union

from fastapi import FastAPI
import os

import uvicorn

from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import FileResponse
# from lib_paper.obj_setting import folder_path
# from lib_paper import file_rd


app = FastAPI()


app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

folder_path = 'lib_paper\测试'


def paper_names(path_= folder_path):
    entries = os.listdir(path_)
    files = [entry for entry in entries if os.path.isfile(os.path.join(folder_path, entry))]

    return files

# @app.get("/")
# def read_root():
#     return {"Hello": "World"}


@app.get("/items/{item_id}")
def read_item(item_id: int, q: Union[str, None] = None):
    return {"item_id": item_id, "q": q}


@app.get("/papers/all")
def read_file_names():
    items_all = paper_names(path_= folder_path)
    f_names = {'files': items_all}
    return f_names


@app.get("/papers/{file_name}")
def deliver_item(file_name: str):
    filne_path = f"{folder_path}/{file_name}"
    file_tp = file_name.split('.')[-1]
    return FileResponse(filne_path, media_type=f"application/{file_tp}", filename=f"{file_name}")


if __name__ == '__main__':
    uvicorn.run(app='api_fast:app', host="127.0.0.1", port=8000, reload=True)

